package com.xwj.nio.netty.basic;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * netty实现消息丢弃功能
 *
 * @author xwj
 * @date 2020/6/11
 */
public class DiscardServer {
    private int port;

    public DiscardServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        // 创建反应器线程组
        // 负责新连接的监听和接受
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // 负责IO事件的处理
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            // 设置反应器线程组
            b.group(bossGroup, workerGroup);
            // 设置io通道类型
            b.channel(NioServerSocketChannel.class);
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                /**
                 * 有连接到达时会创建一个通道
                 * @param ch
                 * @throws Exception
                 */
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    // 每一个通道的子通道，都有一条ChannelPipeline流水线，它的内部有一个双向的链表
                    // 向子通道流水线添加一个handler处理器
                    ch.pipeline().addLast(new DiscardServerHandler());
                }
            });
            b.option(ChannelOption.SO_BACKLOG, 128);
            // 缓冲区池化配置
            b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            b.childOption(ChannelOption.SO_KEEPALIVE, true);
            b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

            // 绑定服务器，同步阻塞直到绑定成功
            ChannelFuture f = b.bind(port).sync();
            System.out.println("服务器启动成功，端口：" + port);

            // 等待通道关闭的异步任务执行结束
            // 服务监听通道会一直等待，直到通道关闭的异步任务执行结束
            f.channel().closeFuture().sync();
        } finally {
            // 释放所有资源（创建的线程）
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new DiscardServer(8888).run();
    }
}
